/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package devbureau.servlet;

import devbureau.fstore.common.Pair;
import devbureau.fstore.common.StoreFactory;
import flexjson.JSONSerializer;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author admin
 */
public class AjaxServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(AjaxServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            String methodName = request.getParameter(Constants.METHOD_NAME);
            log.debug("processRequest try to invoke method => " + methodName );
            this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class)
                           .invoke(this, request, response);
        }catch(Throwable thr){
            log.error("Error while processing ajax req", thr);
        }
    }

    public void getCustomers(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String partialLabel = req.getParameter(Constants.CUSTOMER_QUERY);
        log.debug("getCustomers partialLabel["+partialLabel+"]");

        if(req.getCharacterEncoding() == null){
            partialLabel = chromeCostyl(partialLabel);
            log.debug("getCustomers decoded partialLabel["+partialLabel+"]");
        }
        
        List<Pair<Integer,String>> results = StoreFactory.getStore().getAjaxCustomers(partialLabel);
        resp.setContentType(Constants.JSON_CONTENT_TYPE);
        resp.setCharacterEncoding("windows-1251");
        resp.getWriter().append(new JSONSerializer().serialize(results));
        resp.flushBuffer();
    }

    /** Chrome doesn't set charSet for POST content*/
    private String chromeCostyl(String isoString) {
        String utf8String = null;
        if (null != isoString && !isoString.equals("")) {
            try {
                byte[] stringBytesISO = isoString.getBytes("ISO-8859-1");
                utf8String = new String(stringBytesISO, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        } else {
            utf8String = isoString;
        }
        return utf8String;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}
